﻿// In place editor from http://blog.fawnanddoug.com/2012/05/inline-editor-custom-binding-for.html
ko.bindingHandlers.jeditable = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var options = allBindingsAccessor().jeditableOptions || {};

        if (!options.onblur) {
            options.onblur = 'submit';
        }

        $(element).editable(function (value, params) {
            valueAccessor()(value);
            return value;
        }, options);

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).editable("destroy");
        });
    },

    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).editable().html(value);
    }
};

ko.bindingHandlers.datetime = {
    init: function (element, valueAccessor, allBindingsAccessor) {

    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        var self = $(element);
        var value = ko.utils.unwrapObservable(valueAccessor());
        self.attr("datetime", value + "Z");

        if (self.data('timeago')) {
            var datetime = $.timeago.datetime(self);
            var distance = (new Date().getTime() - datetime.getTime());
            var inWords = $.timeago.inWords(distance);

            // Update cache and displayed text..
            self.data('timeago', { 'datetime': datetime });
            self.text(inWords);
        } else {
            // timeago hasn't been applied to this node -> we do that now!
            self.timeago();
        }
    }
};

ko.bindingHandlers.accordion = {
    init: function (element, valueAccessor) {
        var options = valueAccessor() || {};
        setTimeout(function () {
            $(element).accordion(options);
        }, 0);

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).accordion("destroy");
        });
    },
    update: function (element, valueAccessor) {
        var options = valueAccessor() || {};
        $(element).accordion("destroy").accordion(options);
    }
}